package com.wty.emp.service;

import com.wty.commons.exception.InsertException;
import com.wty.commons.exception.UpdateException;
import com.wty.commons.id.IdWorker;
import com.wty.emp.mapper.EmpMapperWty;
import com.wty.emp.mapper.JobMapperWty;
import com.wty.emp.model.EmpJobWty;
import com.wty.emp.pojo.EmpWty;
import com.wty.emp.pojo.JobWty;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author:wangtianyu
 * @Date：Created on 2020/4/20 0020 20:52
 */
@Service
public class EmpServiceWty {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private EmpMapperWty empMapper;

    @Autowired
    private JobMapperWty jobMapper;

    /*新增员工*/
    @Transactional(rollbackFor = RuntimeException.class) // 事务 数据回滚
    public EmpWty addEmp(EmpWty emp) throws Exception {
        emp.setEmpid(idWorker.nextId());
        int count = empMapper.insert(emp);
        if (count == 0) {
            throw new InsertException("插入失败");
        }
        return emp;
    }

    /*修改员工信息*/
    @Transactional(rollbackFor = RuntimeException.class)
    public EmpWty updateEmp(Long id, EmpWty emp) throws Exception {
        emp.setEmpid(id);
        int count = empMapper.updateById(emp);
        if (count == 0) {
            throw new UpdateException("更新失败");
        }
        return empMapper.selectById(id);
    }

    /*条件查询*/
    public List<EmpJobWty> searchByExample(Map<String, Object> map) throws Exception {
        List<EmpWty> emps = empMapper.selectByMap(map);
        List<JobWty> jobs = jobMapper.selectList(null);
        // 将jobs封装到一个map中
        Map<Long,JobWty> jobMap = new HashMap<>();
        for (int i = 0; i < jobs.size(); i++) {
            JobWty job = jobs.get(i);
            jobMap.put(job.getJobid(),job);
        }
        // 补全EmpJob数据
        List<EmpJobWty> empJobs = emps.stream().map(emp -> {
            EmpJobWty empJob = new EmpJobWty();
            BeanUtils.copyProperties(emp, empJob); // 将emp的数据拷贝到empJob
            empJob.setJob(jobMap.get(emp.getJobid()));
            return empJob;
        }).collect(Collectors.toList());
        return empJobs;
    }


    /*遍历*/
    public List<EmpWty> selectList()throws Exception {
        return empMapper.selectList(null);
    }
}
